package com.yuzhi.common.annotation;


import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DynamicLocalDateTimeSerializer extends JsonSerializer<LocalDateTime>
        implements ContextualSerializer {

    private String pattern;

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property)
            throws JsonMappingException {
        LocalDateTimeFormat annotation = property.getAnnotation(LocalDateTimeFormat.class);
        if (annotation != null) {
            this.pattern = annotation.value();
        } else {
            this.pattern = "yyyy-MM-dd HH:mm:ss"; // 默认格式
        }
        return this;
    }

    @Override
    public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider)
            throws IOException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        gen.writeString(value.format(formatter));
    }
}
